package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class StorageTccActionImpl implements StorageTccAction {
    @Autowired
    private StorageMapper storageMapper;
    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx, Long productId, Integer count) {
//        查询是否有足够库存
        Storage s = storageMapper.selectByProductId(productId);
        if (s.getResidue()<count){
            throw new RuntimeException("库存不足");
        }
//        库存充足，可用-->冻结
        storageMapper.updateResidueToFrozen(productId, count);
        ResultHolder.setResult(StorageTccAction.class, ctx.getXid(), "p");
        return true;
    }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }
//        冻结--->已使用
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid())==null){
            return true;
        }
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateResidueToFrozen(productId, count);
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
}
